//
//  KLSettingViewController.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "MCPersonalViewController.h"
#import "STPhotoUrlImageBrowerController.h"
#import "NSBundle+STSystemTool.h"
#import "MCAreaPickerViewController.h"
@interface MCPersonalViewController ()<STPhotoUrlImageBrowerControllerDelegate,STActionSheetDelegate>
@property(nonatomic, strong) NSArray  <STTableEasyModel*>                   *dataSouce;
@property(nonatomic, strong) STButton                     *iconButton;
@property(nonatomic, strong) STPhotoUrlImageBrowerController                     *pickerVC;
@property(nonatomic, strong) STUrlPhotoModel                     *imageModel;

@end

@implementation MCPersonalViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑个人信息";
    [self configSubView];
    [self reloadData];
    [TMUtils sendMyInfoRequestWithHandle:^(MCUserModel *user) {
        self.userModel = user;
        [self reloadData];
    }];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)updateData{
    
    [TMUtils sendMyInfoRequestWithHandle:^(MCUserModel *user) {
        self.userModel = user;
        [self reloadData];
    }];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                title:nil
                                           titleColor:nil
                                            titleFont:0
                                         cornerRadius:20
                                      backgroundColor:nil
                                      backgroundImage:[UIImage imageNamed:@"reba1"]
                                                image:nil];
    [self.iconButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedIconCell];
    }];
    
    // [self configTableFooter];
}
- (void)configTableFooter{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth , 44)
                                                        title:@"退出登录"
                                                   titleColor:FirstTextColor
                                                    titleFont:18
                                                 cornerRadius:0
                                              backgroundColor:[UIColor whiteColor]
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLogoutButton];
    }];
    confimButton.st_centerY = 50;
    [confimButton st_showTopLine];
    [confimButton st_showBottomLine];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    self.tableView.tableFooterView = footer;
}
- (void)reloadData{
    
    MCUserModel * user = STUserManger.defult.loginedUser;
    
    [self.iconButton sd_setBackgroundImageWithURL:MCRealImageUrl(user.user_icon) forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"reba1"]
     ];

    NSString * genderStr = @"男";
    if (user.sex.integerValue == 2) {
        genderStr = @"女";
    }
    NSString * area = [NSString stringWithFormat:@"%@ %@",user.province,user.city];
    NSArray * sectionOne = @[
                             [[STTableEasyModel alloc] initWithTextString:@"头像" accessoryView:self.iconButton],
                             [[STTableEasyModel alloc] initWithTextString:@"昵称"
                                                             detailString:user.user_nick],
                             [[STTableEasyModel alloc] initWithTextString:@"性别"
                                                             detailString:genderStr],
                             [[STTableEasyModel alloc] initWithTextString:@"所在地区"
                                                             detailString:area]
                             ];

    
    
    self.dataSouce = sectionOne;
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 24;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.textLabel.text = model.textString;
    cell.detailTextLabel.text = model.detailString;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.accessoryType = model.accessoryType;
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if ([model.textString isEqualToString:@"头像"]) {
        [self onSelectedIconCell];
    }
    if ([model.textString isEqualToString:@"昵称"]) {
        [self onSelectedNickNameCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"真实姓名"]) {
        [self onSelctedRealNameCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"性别"]) {
        [self onSelctedGenderCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"出生日期"]) {
        [self onSelctedDateCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"职业"]) {
        [self onSelctedWorkCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"所在地区"]) {
        [self onSelctedAreaCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"个性签名"]) {
        [self onSelectedNickNameCellWithIndexPath:indexPath model:model];
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSelectedIconCell{
    STUrlPhotoModel * model = [STUrlPhotoModel new];
    model.thumbImage = self.iconButton.currentBackgroundImage;
    if (self.userModel) {
        model.thumbImageUrl = @"";
    }
    self.imageModel = model;
    self.pickerVC = [[STPhotoUrlImageBrowerController alloc] initWithArray:@[model] curentIndex:0];
    self.pickerVC.shouldHideBottomView = YES;
    self.pickerVC.STPhotoUrlImageBrowerControllerdelegate = self;
    self.pickerVC.themeColor = FirstTextColor;
    [self presentViewController:self.pickerVC animated:NO completion:nil];
}
- (void)onSelectedNickNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
//                                                              model.detailString = text;
//                                                              [self.tableView reloadData];
                                                              [self sendChangeNickNameRequest:text withModel:model];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)onSelctedRealNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              model.detailString = text;
                                                              [self.tableView reloadData];
                                                              //                                                              [self sendChangeNickNameRequest:text withModel:model];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)onSelctedGenderCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSArray * array = @[@"男",@"女"];
    [self showActionSheet:array andWithBlock:^(int tag) {
//        model.detailString = array[tag];
//        [self.tableView reloadData];
        [self sendChangeGenderRequest:array[tag] withModel:model];
    }];
}
- (void)onSelctedDateCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    STPickerViewController * pickerVC = [[STPickerViewController alloc] initWithDefualtDatePickerWithHandle:^(NSDate *date) {
        model.detailString = date.st_yyyyMMddByLineWithDate;
        [self.tableView reloadData];
    }];
    [self presentViewController:pickerVC animated:NO completion:nil];
}
- (void)onSelctedWorkCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSArray * array = @[@"ios",@"Android",@"php",@"java"];
    STPickerViewController * pickerVC = [[STPickerViewController alloc] initWithPickerArray:@[array] andWithHandle:^(NSArray<NSString *> *stringArray) {
        model.detailString = stringArray.lastObject;
        [self.tableView reloadData];
    }];
    [self presentViewController:pickerVC animated:NO completion:nil];
}
- (void)onSelctedAreaCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    MCAreaPickerViewController * vc = [MCAreaPickerViewController new];
    [vc setOnSlectedHandle:^(NSString *province, NSString *provinceCode, NSString *city, NSString *cityCode) {
         [self sendChangeAreaRequest:province provinceCode:provinceCode city:city cityCode:cityCode withModel:model];
    }];
    [self presentViewController:vc animated:NO completion:nil];
    
}
#pragma mark --STPhotoUrlImageBrowerControllerDelegate
- (UIView*)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STUrlPhotoModel*)model{
    return self.iconButton;
}
- (void)rightBarActionFromController:(STPhotoUrlImageBrowerController*)controller currentIndexPath:(NSIndexPath *)curentIndexpath{
    
    STActionSheet * actionSheet = [[STActionSheet alloc] initWithTitle:nil
                                                          buttonTitles:@[@"拍照",@"从手机相册选择",@"保存图片"] cancelTitle:@"取消"
                                                              delegate:self
                                   ];
    [actionSheet show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.pickerVC showTakePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 1) {
        [self.pickerVC showchosePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 2) {
        [PHPhotoLibrary saveImageToAssetsLibrary:self.iconButton.currentBackgroundImage
                                     libraryName:NSBundle.st_applictionDisplayName successHandle:^{
                                         [SVProgressHUD showSuccessWithStatus:@"保存到相册成功"];
                                     } errorHandle:^(STSaveImageError error) {
                                         
                                     }];
    }
}
#pragma mark --Action Method
- (void)onSelectedLogoutButton{
    [self showAlertCancelAndConfirm:@"确定要退出登录吗?" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            //           [[STUserManger defult] removeUserPreferce];
            //            STNavigationController * nav = [[TMNavgationViewController alloc] initWithRootViewController:[BLLoginHomeViewController new]];
            //            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }
    }];
    
}
#pragma mark --NetWork Method
//修改昵称
- (void)sendChangeNickNameRequest:(NSString*)nickName withModel:(STTableEasyModel*)model{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/savePersonalSetting"];
    if ([STUserManger defult].loginedUser.userID.description.length) {
        [dic setObject:[STUserManger defult].loginedUser.userID.description forKey:@"uid"];
    }
    if ([STUserManger defult].loginedUser.user_icon.length) {
        [dic setObject:[STUserManger defult].loginedUser.user_icon forKey:@"user_icon"];
    }
    if (nickName.length) {
        [dic setObject:nickName forKey:@"user_nick"];
    }
    if (self.userModel.sex) {
        [dic setObject:self.userModel.sex forKey:@"sex"];
    }
    if (self.userModel.province_id) {
        [dic setObject:self.userModel.province_id forKey:@"province"];
    }
    if (self.userModel.city_id) {
        [dic setObject:self.userModel.city_id forKey:@"city"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 model.detailString = nickName;
                                                 [self.tableView reloadData];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
    
}
//修改昵昵称
- (void)sendChangeGenderRequest:(NSString*)gender withModel:(STTableEasyModel*)model{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * genderCode = @"1";
    if ([gender isEqualToString:@"女"]) {
        genderCode = @"2";
    }
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/savePersonalSetting"];
    if ([STUserManger defult].loginedUser.userID.description.length) {
        [dic setObject:[STUserManger defult].loginedUser.userID.description forKey:@"uid"];
    }
    if ([STUserManger defult].loginedUser.user_icon.length) {
        [dic setObject:[STUserManger defult].loginedUser.user_icon forKey:@"user_icon"];
    }
    if (genderCode.length) {
        [dic setObject:genderCode forKey:@"sex"];
    }
    if (self.userModel.user_nick.length) {
        [dic setObject:self.userModel.user_nick forKey:@"user_nick"];
    }
    if (self.userModel.province_id) {
        [dic setObject:self.userModel.province_id forKey:@"province"];
    }
    if (self.userModel.city_id) {
        [dic setObject:self.userModel.city_id forKey:@"city"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 model.detailString = gender;
                                                 [self.tableView reloadData];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
    
}
//修改地址
- (void)sendChangeAreaRequest:(NSString*)province provinceCode:(NSString*)provinceCode city:(NSString*)city cityCode:(NSString*)cityCode withModel:(STTableEasyModel*)model{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/savePersonalSetting"];
    if ([STUserManger defult].loginedUser.userID.description.length) {
        [dic setObject:[STUserManger defult].loginedUser.userID.description forKey:@"uid"];
    }
    if ([STUserManger defult].loginedUser.user_icon.length) {
        [dic setObject:[STUserManger defult].loginedUser.user_icon forKey:@"user_icon"];
    }
    if (provinceCode.length) {
        [dic setObject:provinceCode forKey:@"province"];
    }
    if (cityCode.length) {
        [dic setObject:cityCode forKey:@"city"];
    }
    if (self.userModel.user_nick.length) {
        [dic setObject:self.userModel.user_nick forKey:@"user_nick"];
    }
    if (self.userModel.sex) {
        [dic setObject:self.userModel.sex forKey:@"sex"];
    }
    if (self.userModel.province.length) {
        [dic setObject:self.userModel.province forKey:@"province"];
    }
    if (self.userModel.city.length) {
        [dic setObject:self.userModel.city forKey:@"city"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 model.detailString = [NSString stringWithFormat:@"%@%@",province,city];
                                                 [self.tableView reloadData];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
    
}
- (void)sendIconChangeRequest:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/app_upload_img"];
    [[STNetWrokManger defaultClient] imageRequestWithPath:url
                                               parameters:nil
                                                    image:image
                                                imageName:@"group_icon"
                                                 progress:^(NSProgress *progress) {
                                                     
                                                 } success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                     
                                                     NSString * dataStr =  [[responseObject firstObject] description];
                                                     [self sendIconUrlChangedRequestWithFace:dataStr image:image];
                                                     
                                                 } failure:^(NSString *stateCode, STError *error) {
                                                     
                                                     
                                                 }];
   
}
- (void)sendIconUrlChangedRequestWithFace:(NSString*)face image:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/System/savePersonalSetting"];
    if ([STUserManger defult].loginedUser.userID.description.length) {
        [dic setObject:[STUserManger defult].loginedUser.userID.description forKey:@"uid"];
    }
    if (face.length) {
        [dic setObject:face forKey:@"user_icon"];
    }
    if (self.userModel.user_nick.length) {
        [dic setObject:self.userModel.user_nick forKey:@"user_nick"];
    }
    if (self.userModel.sex) {
        [dic setObject:self.userModel.sex forKey:@"sex"];
    }
    if (self.userModel.province_id) {
        [dic setObject:self.userModel.province_id forKey:@"province"];
    }
    if (self.userModel.city_id) {
        [dic setObject:self.userModel.city_id forKey:@"city"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 //NSString * dataStr =  responseObject[@"data"];
                                                 [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                                                 self.imageModel.originImage = image;
                                                 [self.pickerVC reloadData];
                                                 [SVProgressHUD showSuccessWithStatus:@"修改头像成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

- (void)sendMyInfoRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/MemberListAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.userModel = [MCUserModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

